# -*- coding: utf-8 -*-

import time
from log.logger import logger
from misc.exec_cmd import (
    exec_cmd,
    safe_exec_cmd,
)


def check_ping(ip, tries=2, delay=1):
    check_ip_count = 0
    while check_ip_count < tries:
        result = exec_cmd('ping -c 1 -w 2 {0}'.format(ip))
        if result['ret'] != 0:
            check_ip_count += 1
            time.sleep(delay)
        else:
            break
    else:
        logger.error("Check the host [{0}] ping connection failed!".format(ip))
        return -1

    return 0


def check_ssh(ip, tries=3, delay=3):
    check_ssh_count = 0
    while check_ssh_count < tries:
        result = exec_cmd('ssh -o ConnectTimeout=2 root@{0} echo'.format(ip))
        if result['ret'] != 0:
            check_ssh_count += 1
            time.sleep(delay)
        else:
            break
    else:
        logger.error("Check the host [{0}] ssh connection failed!".format(ip))
        return -1

    return 0


def get_local_ips():
    default_gateway_dev = exec_cmd("ip route | awk '/^default/ {print $5}'")['out']
    ips = exec_cmd("ip -f inet -o addr | awk '{print $2,$4}' | awk -F '/' '{print $1}'")['out'].split('\n')

    ips_dict = {
        value.split()[0] : value.split()[1]
        for value in ips
    }

    if default_gateway_dev:
        ips_dict['default'] = ips_dict[default_gateway_dev]

    return ips_dict
    

def get_firstbox_address(default_dev = 'eth0'):
    # get the default ip as firstbox address
    local_ips = get_local_ips()

    if local_ips.has_key('default'):
        firstbox_address = local_ips['default']
    elif local_ips.has_key(default_dev):
        firstbox_address = local_ips[default_dev]
    else:
        logger.error("Can not get the firstbox address, please check the default ip route and eth0!")
        return None

    return firstbox_address